{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "25aba748",
   "metadata": {},
   "source": [
    "## grad fn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f16be65e",
   "metadata": {},
   "source": [
    "- MulBackward0\n",
    "- MeanBackward0\n",
    "- ..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a8799d5",
   "metadata": {},
   "source": [
    "## `requires_grad = True`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "3aec21fe",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-11-14T13:12:52.080492Z",
     "start_time": "2023-11-14T13:12:52.067867Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([8.], grad_fn=<MulBackward0>)\n",
      "tensor(8., grad_fn=<MeanBackward0>)\n",
      "tensor([2.], requires_grad=True) True\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "# 创建一个可跟踪梯度的张量\n",
    "x = torch.tensor([2.0], requires_grad=True)\n",
    "\n",
    "# 对张量进行一些操作\n",
    "# 2x^2\n",
    "y = x * x * 2\n",
    "print(y)\n",
    "z = y.mean()\n",
    "print(z)\n",
    "print(x, x.is_leaf)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "86b1b9dd",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-11-14T13:12:14.120433Z",
     "start_time": "2023-11-14T13:12:14.111021Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([8.])\n"
     ]
    }
   ],
   "source": [
    "# 执行反向传播\n",
    "z.backward()\n",
    "\n",
    "# 输出梯度, 4x\n",
    "print(x.grad)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
